package com.jiantong.work.impl.manager;

import com.google.common.collect.Maps;
import com.jiantong.common.util.UserUtil;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.work.enums.*;
import com.jiantong.work.impl.dao.*;
import com.jiantong.work.model.*;
import com.jiantong.work.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by niufei on 2017/3/22.
 *
 */
@Component
public class ButcherReportManager {

    private final ButcherReportDao butcherReportDao;

    private final ReportHandleResumeDao reportHandleResumeDao;

    private final ButcherReportSurveyRecordDao butcherReportSurveyRecordDao;

    private final ButcherAdmissionInspectionDao butcherAdmissionInspectionDao;

    private final HarmlessDao harmlessDao;

    @Autowired
    public ButcherReportManager(ButcherReportDao butcherReportDao,
                                ReportHandleResumeDao reportHandleResumeDao,
                                ButcherReportSurveyRecordDao butcherReportSurveyRecordDao,
                                HarmlessDao harmlessDao,
                                ButcherAdmissionInspectionDao butcherAdmissionInspectionDao) {
        this.butcherReportDao = butcherReportDao;
        this.reportHandleResumeDao = reportHandleResumeDao;
        this.butcherReportSurveyRecordDao = butcherReportSurveyRecordDao;
        this.harmlessDao = harmlessDao;
        this.butcherAdmissionInspectionDao = butcherAdmissionInspectionDao;
    }

    /**
     * 新建屠宰检疫的单据 -- 屠宰端
     * @param butcherReport 单据对象
     * @param toStatus 到状态
     * @return Map<String , Object>
     */
    @Transactional
    public Map<String , Object> createButcherReport(ButcherReport butcherReport , Integer toStatus, List<String> remainderEars){
        Integer fromStatus = butcherReport.getStatus();
        ReportHandleResume reportHandleResume;
        Map<String , Object> map = Maps.newHashMap();

        LoginUser loginUser = UserUtil.getCurrentUser();
        String prefix = "T";
        prefix = Utils.createPrefix(prefix,loginUser);
        String number = Utils.create(prefix,butcherReportDao.findCurrentMaxNumber(prefix));
        butcherReport.setNumber(number);
        butcherReport.setDeleteFlag(DocumentsDeleteFlag.NORMAL.value());

        if(toStatus != null && !fromStatus.equals(toStatus)){
            butcherReport.setStatus(toStatus);
            butcherReportDao.create(butcherReport);
            map.put("butcherReportId",butcherReport.getId());

            reportHandleResume = new ReportHandleResume();
            reportHandleResume.setReportId(butcherReport.getId());
            reportHandleResume.setReportNumber(butcherReport.getNumber());
            reportHandleResume.setUserId(loginUser.getId());
            reportHandleResume.setUserName(loginUser.getName());
            reportHandleResume.setFromStatus(fromStatus);
            reportHandleResume.setToStatus(toStatus);
            reportHandleResume.setType(DocumentsType.SLAUGHTER_QUARANTINE.value());//屠宰检疫

            reportHandleResumeDao.create(reportHandleResume);
            map.put("reportHandleResumeId",reportHandleResume.getId());

            ButcherAdmissionInspection butcherAdmissionInspection = butcherAdmissionInspectionDao.findById(butcherReport.getAdmissionInspectionId());
            butcherAdmissionInspection.setId(butcherReport.getAdmissionInspectionId());
            butcherAdmissionInspection.setButcherSelected(1);
            butcherAdmissionInspection.setRemainder(butcherAdmissionInspection.getRemainder() - butcherReport.getQuantity());
            butcherAdmissionInspection.setSlaughterings(butcherAdmissionInspection.getSlaughterings() + butcherReport.getQuantity());
            butcherAdmissionInspection.setRemainderEars(remainderEars);
            butcherAdmissionInspectionDao.updateButcherSelected(butcherAdmissionInspection);
        }else {
            butcherReportDao.create(butcherReport);
            map.put("butcherReportId",butcherReport.getId());
        }
        return map;
    }

    /**
     * 更新屠宰检疫的单据 -- 屠宰端
     * @param butcherReport 单据对象
     * @param toStatus 到状态
     * @return Map<String , Object>
     */
    @Transactional
    public Map<String , Object> updateButcherReport(ButcherReport butcherReport , Integer toStatus,List<String> remainderEars){
        Integer fromStatus = butcherReport.getStatus();
        ReportHandleResume reportHandleResume;
        Map<String , Object> map = Maps.newHashMap();
        Boolean flagButcherReport;

        if(toStatus != null && !fromStatus.equals(toStatus)){
            butcherReport.setStatus(toStatus);
            flagButcherReport = butcherReportDao.update(butcherReport);
            map.put("flagButcherReport",flagButcherReport);

            reportHandleResume = new ReportHandleResume();
            reportHandleResume.setReportId(butcherReport.getId());
            reportHandleResume.setReportNumber(butcherReport.getNumber());
            reportHandleResume.setUserId(UserUtil.getCurrentUser().getId());
            reportHandleResume.setUserName(UserUtil.getCurrentUser().getName());
            reportHandleResume.setFromStatus(fromStatus);
            reportHandleResume.setToStatus(toStatus);
            reportHandleResume.setType(DocumentsType.SLAUGHTER_QUARANTINE.value());

            reportHandleResumeDao.create(reportHandleResume);
            map.put("reportHandleResumeId",reportHandleResume.getId());

            ButcherAdmissionInspection butcherAdmissionInspection = butcherAdmissionInspectionDao.findById(butcherReport.getAdmissionInspectionId());
            butcherAdmissionInspection.setId(butcherReport.getAdmissionInspectionId());
            butcherAdmissionInspection.setButcherSelected(1);
            butcherAdmissionInspection.setRemainder(butcherAdmissionInspection.getRemainder() - butcherReport.getQuantity());
            butcherAdmissionInspection.setSlaughterings(butcherAdmissionInspection.getSlaughterings() + butcherReport.getQuantity());
            butcherAdmissionInspection.setRemainderEars(remainderEars);
            butcherAdmissionInspectionDao.updateButcherSelected(butcherAdmissionInspection);
        }else {
            flagButcherReport = butcherReportDao.update(butcherReport);
            map.put("flagButcherReport",flagButcherReport);
        }
        return map;
    }

    /**
     * 更新屠宰检疫的单据 -- 屠宰端and 政府端
     * @param butcherReport 单据对象
     * @param butcherReportSurveyRecord 单据对象
     * @param toStatus 到状态
     * @return Map<String , Object>
     */
    @Transactional
    public Map<String , Object> saveButcherReportAndSurveyRecord(ButcherReport butcherReport, ButcherReportSurveyRecord butcherReportSurveyRecord,Integer toStatus ){
        Integer fromStatus = butcherReport.getStatus();
        ReportHandleResume reportHandleResume;
        Map<String , Object> map = Maps.newHashMap();
        Boolean flagButcherReport;
        Boolean flagButcherReportSurveyRecord;

        if(toStatus!= null && !fromStatus.equals(toStatus)){
            butcherReport.setStatus(toStatus);
            flagButcherReport = butcherReportDao.update(butcherReport);
            map.put("flagButcherReport",flagButcherReport);

            if(butcherReportSurveyRecord.getId() == null){
                butcherReportSurveyRecord.setReportId(butcherReport.getId());
                butcherReportSurveyRecordDao.create(butcherReportSurveyRecord);
                map.put("butcherReportSurveyRecordId",butcherReportSurveyRecord.getId());
            }else {
                flagButcherReportSurveyRecord = butcherReportSurveyRecordDao.update(butcherReportSurveyRecord);
                map.put("flagButcherReportSurveyRecord",flagButcherReportSurveyRecord);
            }
            reportHandleResume = new ReportHandleResume();
            reportHandleResume.setReportId(butcherReport.getId());
            reportHandleResume.setReportNumber(butcherReport.getNumber());
            reportHandleResume.setType(DocumentsType.SLAUGHTER_QUARANTINE.value());
            reportHandleResume.setUserId(UserUtil.getCurrentUser().getId());
            reportHandleResume.setUserName(UserUtil.getCurrentUser().getName());
            reportHandleResume.setFromStatus(fromStatus);
            reportHandleResume.setToStatus(toStatus);

            reportHandleResumeDao.create(reportHandleResume);
            map.put("reportHandleResumeId",reportHandleResume.getId());

            //无害化
            if((fromStatus.equals(ButcherReportStatus.ANTEMORTEM_INSPECTION.value()) && butcherReportSurveyRecord.getBeforeSlaughterUnqualifiedQuantity()>0)){
                Harmless harmless = buildHarmless(butcherReport,butcherReportSurveyRecord,fromStatus);
                harmlessDao.create(harmless);
                map.put("harmlessId",harmless.getId());
                butcherReportSurveyRecord.setBeforeSlaughterHarmlessNumber(harmless.getNumber());
                butcherReportSurveyRecord.setBeforeSlaughterHarmlessId(harmless.getId());
                butcherReportSurveyRecordDao.update(butcherReportSurveyRecord);
            }
             if(fromStatus.equals(ButcherReportStatus.SYNCHRONOUS_INSPECTION.value()) && butcherReportSurveyRecord.getSyncUnqualifiedQuantity()>0){
                Harmless harmless = buildHarmless(butcherReport,butcherReportSurveyRecord,fromStatus);
                harmlessDao.create(harmless);
                map.put("harmlessId",harmless.getId());

                butcherReportSurveyRecord.setSyncSlaughterHarmlessId(harmless.getId());
                butcherReportSurveyRecord.setSyncSlaughterHarmlessNumber(harmless.getNumber());
                butcherReportSurveyRecordDao.update(butcherReportSurveyRecord);
            }
        }
        return map;
    }

    /**
     * 构建无害化的对象
     * @param butcherReport 屠宰检疫的对象 --- 屠宰端
     * @param butcherReportSurveyRecord 屠宰检疫的对象 --- 政府端
     * @param fromStatus 从状态
     * @return 无害化的对象
     */
    private Harmless buildHarmless(ButcherReport butcherReport, ButcherReportSurveyRecord butcherReportSurveyRecord,Integer fromStatus) {
        Harmless harmless = new Harmless();
        LoginUser loginUser = UserUtil.getCurrentUser();
        String prefix = "WZ";
        if(fromStatus.equals(ButcherReportStatus.ANTEMORTEM_INSPECTION.value())){ //宰前检查
            harmless.setReportType(DocumentsType.ANTEMORTEM_INSPECTION.value());
            harmless.setQuantity(butcherReportSurveyRecord.getBeforeSlaughterUnqualifiedQuantity().floatValue());
            harmless.setAnimalType(butcherReport.getProductType());
            harmless.setUnit(butcherReport.getUnit());
        }else if(fromStatus.equals(ButcherReportStatus.SYNCHRONOUS_INSPECTION.value())){//同步检疫
            prefix = "WT";
            harmless.setReportType(DocumentsType.SYNCHRONOUS_INSPECTION.value());
            harmless.setQuantity(butcherReportSurveyRecord.getSyncUnqualifiedQuantity());
            //TODO  判断extraJson
            harmless.setAnimalType(butcherReport.getProductType());
            harmless.setProductType(calculateProductType(butcherReportSurveyRecord.getExtra()));//todo
            harmless.setUnit(Unit.KG.value());//todo
        }
        prefix = Utils.createPrefix(prefix,loginUser);
        String number = Utils.create(prefix,harmlessDao.findCurrentMaxNumber(prefix));
        harmless.setNumber(number);
        harmless.setReportId(butcherReport.getId());
        harmless.setReportNumber(butcherReport.getNumber());
        harmless.setStatus(HarmlessStatus.UNCOMMITTED.value());
        harmless.setButcherFactoryId(butcherReport.getButcherFactoryId());
        harmless.setButcherFactoryName(butcherReport.getButcherFactoryName());
        harmless.setFactoryOwnerId(butcherReport.getUserId());
        harmless.setFactoryOwnerName(butcherReport.getUserName());
        harmless.setIsLocal(butcherReport.getIsLocal());
        harmless.setQuarantineUserId(loginUser.getId());
        harmless.setQuarantineUserName(loginUser.getName());
        harmless.setDeleteFlag(DocumentsDeleteFlag.NORMAL.value());

        return harmless;
    }

    private String calculateProductType(Map<String, Float> extra) {
        Float headerNum = extra.get("head");
        Float ketoneBody = extra.get("carcass");
        Float internal = extra.get("visceral");

        if(headerNum != 0f && ketoneBody != 0f && internal != 0f){
            return ProductType.HEAD_INTERNAL_KET.toString();
        }
        if(headerNum != 0f && ketoneBody != 0f ){
            return ProductType.HEAD_KET.toString();
        }
        if(headerNum != 0f && internal == 0f){
            return ProductType.HEAD.toString();
        }
        if(ketoneBody != 0f && internal == 0f){
            return ProductType.KET.toString();
        }
        if(headerNum != 0f ){
            return ProductType.HEAD_INTERNAL.toString();
        }
        if(ketoneBody != 0f ){
            return ProductType.INTERNAL_KET.toString();
        }
        if(internal != 0f){
            return ProductType.INTERNAL.toString();
        }
        return null;
    }
}
